package com.zrrd.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zrrd.reggie.bean.ShoppingCart;
import com.zrrd.reggie.common.ThreadLocalUtil;
import com.zrrd.reggie.mapper.ShoppingCartMapper;
import com.zrrd.reggie.service.ShoppingCartService;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCartMapper, ShoppingCart> implements ShoppingCartService {


    @Override
    public ShoppingCart addCart(ShoppingCart shoppingCart) {
        //有存入线程对象的id
        Long userId = ThreadLocalUtil.getCurrentId();
        //将这个赋值给购物车对象
        shoppingCart.setUserId(userId);
        QueryWrapper<ShoppingCart> wrapper =new QueryWrapper<>();
        wrapper.eq("user_id",userId);
        //看他是不是菜品
        Long dishId = shoppingCart.getDishId();
        if (dishId!=null){
            wrapper.eq("dish_id",dishId);
        }else {
            wrapper.eq("setmeal_id",shoppingCart.getSetmealId());
        }
        //查询看有无，有加number
        ShoppingCart cart = this.getOne(wrapper);
        if (cart!=null){
            Integer number = cart.getNumber() + 1;
            cart.setNumber(number);
           /* shoppingCart.setAmount(shoppingCart.getAmount()*number);*/
            this.updateById(cart);
        }else {
            shoppingCart.setNumber(1);
            shoppingCart.setCreateTime(LocalDateTime.now());
            this.save(shoppingCart);
            cart =shoppingCart;
        }
        return cart;
    }
}
